package com.zhzhinn.activity;


import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Build;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.edgclub.edg.Constant;
import com.edgclub.edg.GuZhiApplication;
import com.edgclub.edg.R;
import com.edgclub.edg.activity.GzBaseTooolBarActivity;
import com.edgclub.edg.activity.GzMainActivity;
import com.edgclub.edg.activity.MultiImageSelectorActivity;
import com.edgclub.edg.api.UserApi;
import com.edgclub.edg.http.async.AsyncHttpResponseHandler;
import com.edgclub.edg.http.async.RequestParams;
import com.edgclub.edg.huanxin.DemoHelper;
import com.edgclub.edg.huanxin.activity.ContextMenuActivity;
import com.edgclub.edg.huanxin.db.DemoDBManager;
import com.edgclub.edg.model.User;
import com.edgclub.edg.model.result.UserData;
import com.edgclub.edg.utils.GlideUtil.GlideUtils;
import com.edgclub.edg.utils.util.JSONHelper;
import com.edgclub.edg.utils.util.JsonUtil;
import com.edgclub.edg.utils.util.StringUtils;
import com.edgclub.edg.utils.util.UserPrefUtils;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMTextMessageBody;
import com.hyphenate.easeui.utils.EaseCommonUtils;
import com.hyphenate.util.PathUtil;
import com.zhzhinn.address.AddressManger;
import com.zhzhinn.uc.addresspick.OptionsPickerView;
import com.zhzhinn.uc.addresspick.ProvinceBean;
import com.zhzhinn.uc.addresspick.WheelView;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

public class ZZRegisterSelectIconActivity extends GzBaseTooolBarActivity implements View.OnClickListener {

    private LinearLayout choose_boy, choose_girl;
    private TextView boy_text, girl_text;
    private ImageView userIocn;

    private RelativeLayout useriocn_layout;

    private EditText nick, recommend, innno;
    private TextView address;
    private Button btn_login;
    private GlideUtils glideUtils = new GlideUtils();
    private int sexType = 1;
    private String userPath = "";
    private UserPrefUtils userPrefUtils;
    private User user;
    private boolean isLoad;
    private LinearLayout scan;

    public final static int SCAN_RESULT = 0x0001;

    @Override
    public int getContentView() {
        return R.layout.zz_activity_seleteicon;
    }

    @Override
    public void setTitleBarView() {
        setCustomActionBar();
        title.setText("个人信息");
        main_back.setVisibility(View.VISIBLE);
    }

    @Override
    public void initView() {
        choose_boy = (LinearLayout) findViewById(R.id.choose_boy);
        choose_girl = (LinearLayout) findViewById(R.id.choose_girl);
        boy_text = (TextView) findViewById(R.id.boy_text);
        girl_text = (TextView) findViewById(R.id.girl_text);
        userIocn = (ImageView) findViewById(R.id.userIocn);


        nick = (EditText) findViewById(R.id.nick);
        recommend = (EditText) findViewById(R.id.recommend);
        innno = (EditText) findViewById(R.id.innno);
        address = (TextView) findViewById(R.id.address);
        btn_login = (Button) findViewById(R.id.btn_login);
        useriocn_layout = (RelativeLayout) findViewById(R.id.useriocn_layout);
        scan = (LinearLayout) findViewById(R.id.scan);
        userIocn.setOnClickListener(this);
        useriocn_layout.setOnClickListener(this);
        choose_girl.setOnClickListener(this);
        choose_boy.setOnClickListener(this);
        address.setOnClickListener(this);
        btn_login.setOnClickListener(this);
        scan.setOnClickListener(this);
    }

    @Override
    public void initData() {
        userPrefUtils = new UserPrefUtils(this);
        user = userPrefUtils.getUser();
        if (null == user) user = new User();
        initOptionPicker();
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.useriocn_layout:
            case R.id.userIocn:
                Intent intent2 = new Intent(this, MultiImageSelectorActivity.class);
                intent2.putExtra("selectType", 2);
                // 是否显示拍摄图片
                intent2.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
                // 最大可选择图片数量
                intent2.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, 1);
                // 选择模式
                intent2.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_SINGLE);
//                startActivity(intent2);
                startActivityForResult(intent2, Constant.IMAGE_RESULT);
                break;
            case R.id.choose_boy:
                sexType = 1;
                choose_boy.setBackground(getResources().getDrawable(R.drawable.zz_login_shape_bg6));
                choose_girl.setBackground(getResources().getDrawable(R.drawable.zz_login_shape_bg7));
                boy_text.setTextColor(getResources().getColor(R.color.c5));
                girl_text.setTextColor(getResources().getColor(R.color.c9));
                break;
            case R.id.choose_girl:
                sexType = 0;
                choose_boy.setBackground(getResources().getDrawable(R.drawable.zz_login_shape_bg7));
                choose_girl.setBackground(getResources().getDrawable(R.drawable.zz_login_shape_bg8));
                boy_text.setTextColor(getResources().getColor(R.color.c9));
                girl_text.setTextColor(getResources().getColor(R.color.c5));
                break;
            case R.id.btn_login:
                updateUsetInfo();
                break;
            case R.id.address:
                hideSoftKeyboard();
                pvOptions.show();
                break;
            case R.id.scan:
                Intent intent = new Intent(ZZRegisterSelectIconActivity.this, ZZWeChatCaptureActivity.class);
                startActivityForResult(intent , SCAN_RESULT);
                break;
        }
    }

    private void updateUsetInfo() {
        if (isLoad) return;
//        if(null==userPath||"".equals(userPath)||"null".equals(userPath)){
//            StringUtils.postToast(this,"请上传自己的头像！");
//            return;
//        }
        if ("".equals(nick.getText() + "")) {
            StringUtils.postToast(this, "请您留下大名！");
            return;
        }
        RequestParams userParam = new RequestParams();
        userParam.put("userId", user.getId());
        userParam.put("nick", nick.getText() + "");
        userParam.put("sex", "" + sexType);


        try {
            if (null != userPath && !"".equals(userPath) && !"null".equals(userPath)) {
                userParam.put("logo", new File(userPath));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        new UserApi(this).getUpdateInfo(userParam, new AsyncHttpResponseHandler() {
            @Override
            public void onStart() {
                showDialog("正在提交数据，请稍后...", false);
                isLoad = true;
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                dismissDialog();
                isLoad = false;
                try {
                    String recString = null;
                    recString = new String(responseBody);
                    if (JSONHelper.isSuccess(recString)) {
                        UserData userData = JsonUtil.getMode(recString, UserData.class);
                        if (null != userData && null != userData.getData()) {
                            userPrefUtils.saveUser(userData.getData());
                        }
                        login();
                    } else {
                        StringUtils.postToast(ZZRegisterSelectIconActivity.this, recString + "");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                dismissDialog();
                isLoad = false;
                Toast.makeText(ZZRegisterSelectIconActivity.this, "网络异常，请稍后再试", Toast.LENGTH_SHORT).show();
            }
        });
    }

//    private void icon() {
//        UserParam param = new UserParam();
//        param.setUserId(user.getId());
//        param.setNick(user_name.getText() + "");
//        param.setSex(sexType+"");
//        new UserApi(this).getUpdateInfopost(param, this);
//    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == Constant.IMAGE_RESULT) {
                userPath = data.getStringExtra("userPath") + "";
                useriocn_layout.setVisibility(View.GONE);
                userIocn.setVisibility(View.VISIBLE);
                glideUtils.Glidde_loadCropCircleImage(ZZRegisterSelectIconActivity.this, userPath, userIocn);
            }
            if (requestCode == SCAN_RESULT) {
                if (data != null) {
                    String innnoString = data.getStringExtra("innno");
                    innno.setText(innnoString);
                }
            }
        }
    }


    /**
     * 环信登录
     */
    public void login() {
        if (!EaseCommonUtils.isNetWorkConnected(this)) {
            Toast.makeText(this, R.string.network_isnot_available, Toast.LENGTH_SHORT).show();
            return;
        }

        // After logout，the DemoDB may still be accessed due to async callback, so the DemoDB will be re-opened again.
        // close it before login to make sure DemoDB not overlap
        DemoDBManager.getInstance().closeDB();
        // reset current user name before login
        DemoHelper.getInstance().setCurrentUserName(user.getNick());
        final long start = System.currentTimeMillis();
        // 调用sdk登陆方法登陆聊天服务器
        EMClient.getInstance().login(user.getImid(), userPrefUtils.getPSW(), new EMCallBack() {

            @Override
            public void onSuccess() {
                EMClient.getInstance().updateCurrentUserNick(user.getNick());
                dismissDialog();
                // ** 第一次登录或者之前logout后再登录，加载所有本地群和回话
                // ** manually load all local groups and
                GuZhiApplication.isFirstMianActivity = true;
                Intent intent = new Intent(ZZRegisterSelectIconActivity.this, GzMainActivity.class);
                startActivity(intent);
                finish();
                // 进入主页面
            }

            @Override
            public void onProgress(int progress, String status) {

            }

            @Override
            public void onError(final int code, final String message) {
                runOnUiThread(new Runnable() {
                    public void run() {
                        dismissDialog();
                        Toast.makeText(getApplicationContext(), getString(R.string.Login_failed) + message,
                                Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }


//    @Override
//    public void onStart(String tag) {
//        showDialog("正在提交数据，请稍后...",false);
//        isLoad=true;
//    }
//
//    @Override
//    public void onSuccess(String response, String tag) {
//        dismissDialog();
//        isLoad=false;
//
//            if(JSONHelper.isSuccess(response)){
//                UserData userData= JsonUtil.getMode(response,UserData.class);
//                if(null!=userData&&null!=userData.getData()){
//                    userPrefUtils.saveUser(userData.getData());
//                }
//                login();
//            }else{
//                showToast(JSONHelper.getResultMsg(response));
//        }
//    }
//
//    @Override
//    public void onFaile(VolleyError volleyError, String tag) {
//        dismissDialog();
//        isLoad=false;
//        ResultCode.toastVolleyError(this,volleyError);
//    }

    private void initOptionPicker() {//条件选择器初始化
        provinceBeanList = AddressManger.getInstance().getProvinceBeanList();
        cityList = AddressManger.getInstance().getCityList();
        districtList = AddressManger.getInstance().getDistrictList();
        pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
//                返回的分别是三个级别的选中位置
                String city = provinceBeanList.get(options1).getPickerViewText();
                String address1;
                //  如果是直辖市或者特别行政区只设置市和区/县
                if ("北京市".equals(city) || "上海市".equals(city) || "天津市".equals(city) || "重庆市".equals(city) || "澳门".equals(city) || "香港".equals(city)) {
                    address1 = provinceBeanList.get(options1).getPickerViewText()
                    ;
                } else {
                    address1 = provinceBeanList.get(options1).getPickerViewText()
                            + " " + cityList.get(options1).get(options2)
                    ;
                }
                address.setText(address1);
            }
        })
                /*.setSubmitText("确定")
                .setCancelText("取消")
                .setTitleText("城市选择")
                .setTitleSize(20)
                .setSubCalSize(18)//确定取消按钮大小
                .setTitleColor(Color.BLACK)
                .setSubmitColor(Color.BLUE)
                .setCancelColor(Color.BLUE)
                .setBackgroundColor(Color.WHITE)
                .setLinkage(false)//default is true
                .setCyclic(false, false, false)//循环与否
                .setOutSideCancelable(false)//点击外部dismiss, default true
                .setTitleBgColor(0xFF333333)//标题背景颜色 Night mode
                .setBgColor(0xFF000000)//滚轮背景颜色 Night mode
                .setLabels("省", "市", "区")//设置选择的三级单位
                .setLineSpacingMultiplier(2.0f) //设置两横线之间的间隔倍数（范围：1.2 - 2.0倍 文字高度）
                .setDividerColor(Color.RED)//设置分割线的颜色
                .isDialog(false)//是否设置为对话框模式
                .setOutSideCancelable(false)//点击屏幕中控件外部范围，是否可以取消显示*/
                .setTitleBgColor(getResources().getColor(R.color.c10))//标题背景颜色 Night mode
                .setBgColor(getResources().getColor(R.color.common_bg))//滚轮背景颜色 Night mode
                .setSubmitColor(getResources().getColor(R.color.c14))
                .setCancelColor(getResources().getColor(R.color.c1))
                .setTitleText("")
                .setDividerType(WheelView.DividerType.FILL)
                .setDividerColor(getResources().getColor(R.color.c9))
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(18)//设置滚轮文字大小
                .setSelectOptions(0, 1, 2)  //设置默认选中项
                .isDialog(false)
                .setOutSideCancelable(true)// default is true
                .build();

        pvOptions.setPicker(provinceBeanList, cityList, null);
    }

    //  省份
    ArrayList<ProvinceBean> provinceBeanList = new ArrayList<>();
    //  城市
    ArrayList<List<String>> cityList = new ArrayList<>();
    //  区/县
    ArrayList<List<List<String>>> districtList = new ArrayList<>();
    private OptionsPickerView pvOptions;



}
